import urllib.request
import urllib.parse
import os
import time

# 目标PDF文件名
target_pdf_name = "人工智能对就业市场的影响数据集.pdf"
save_path = os.path.join("d:\D", target_pdf_name)

# 从之前的成功尝试中获取的URL格式
successful_url_template = "https://moor-smile.shec.edu.cn/pdf/{date}/{uuid}/{pdf_name}"

# 其他可能的URL模板
additional_url_templates = [
    "https://moor-smile.shec.edu.cn/rest/pdf/{date}/{uuid}/{pdf_name}",
    "https://moor-smile.shec.edu.cn/files/pdf/{date}/{uuid}/{pdf_name}",
    "https://moor-smile.shec.edu.cn/api/pdf/{date}/{uuid}/{pdf_name}"
]

def download_without_retry(pdf_url):
    """单次尝试下载文件，不进行重试"""
    try:
        print(f"\n尝试URL:")
        print(f"{pdf_url}")
        
        # 创建请求对象，添加用户代理
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'application/pdf,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Connection': 'keep-alive'
        }
        req = urllib.request.Request(pdf_url, headers=headers)
        
        # 尝试连接并下载
        with urllib.request.urlopen(req, timeout=10) as response:
            # 检查响应状态
            if response.status == 200:
                content_type = response.getheader('Content-Type', '')
                content_length = response.getheader('Content-Length', '0')
                
                print(f"状态码: {response.status}")
                print(f"Content-Type: {content_type}")
                print(f"Content-Length: {content_length} 字节")
                
                # 检查是否是PDF文件
                if 'application/pdf' not in content_type:
                    print(f"警告: 响应不是PDF文件，Content-Type: {content_type}")
                    return False
                
                # 读取并保存文件
                with open(save_path, 'wb') as out_file:
                    # 分块读取以处理大文件
                    chunk_size = 8192
                    total_read = 0
                    while True:
                        chunk = response.read(chunk_size)
                        if not chunk:
                            break
                        out_file.write(chunk)
                        total_read += len(chunk)
                        if total_read % 102400 == 0:  # 每读取100KB显示一次进度
                            print(f"已读取: {total_read/1024:.2f} KB")
                
                print(f"总读取字节数: {total_read}")
                
                # 验证文件下载成功
                if os.path.exists(save_path):
                    file_size = os.path.getsize(save_path)
                    print(f"文件保存成功，大小: {file_size} 字节")
                    
                    # 检查文件是否为空
                    if file_size > 0:
                        print(f"PDF文件下载成功！")
                        print(f"保存路径: {save_path}")
                        print(f"文件大小: {file_size/1024/1024:.2f} MB")
                        return True
                    else:
                        print("警告: 下载的文件为空")
                else:
                    print("文件保存失败。")
            else:
                print(f"URL不存在，状态码: {response.status}")
    except urllib.error.HTTPError as e:
        print(f"HTTP错误: {e.code}")
    except urllib.error.URLError as e:
        print(f"URL错误: {e.reason}")
    except Exception as e:
        print(f"下载时发生错误: {e}")
    
    return False

def try_different_urls():
    print(f"尝试下载文件: {target_pdf_name}")
    print(f"保存路径: {save_path}")
    
    # 对PDF名称进行URL编码
    encoded_pdf_name = urllib.parse.quote(target_pdf_name)
    
    # 根据用户提示，链接中的日期一定是0808
    # 尝试更多的UUID组合（只包含20250808日期）
    date_uuid_combinations = [
        ("20250808", "5df60712-8a75-4581-814e-16a203dd27bb"),
        ("20250808", "50b9bf1c-287f-4a58-baa9-071f2db350a6"),
        ("20250808", "84519de1-8bb4-4bd1-b3fa-e610b20d4408"),
        ("20250808", "a1b2c3d4-e5f6-4a5b-8c9d-0123456789ab"),
        ("20250808", "1234abcd-5678-90ef-ab12-34567890abcd"),
        ("20250808", "f9e8d7c6-b5a4-3d2c-1b0a-fedcba987654"),
        ("20250808", "7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d"),
        ("20250808", "4d3c2b1a-5f6e-7d8c-9b0a-1f2e3d4c5b6a")
    ]
    
    # 首先尝试之前成功连接的URL格式
    for date, uuid in date_uuid_combinations:
        pdf_url = successful_url_template.format(date=date, uuid=uuid, pdf_name=encoded_pdf_name)
        if download_without_retry(pdf_url):
            return True
    
    # 如果上述尝试失败，尝试其他URL模板
    for template in additional_url_templates:
        for date, uuid in date_uuid_combinations:
            pdf_url = template.format(date=date, uuid=uuid, pdf_name=encoded_pdf_name)
            if download_without_retry(pdf_url):
                return True
    
    # 如果所有尝试都失败
    print("\n所有URL尝试都失败了。")
    print("可能的原因:")
    print("1. 文件可能不存在或已被移动")
    print("2. 服务器可能限制了访问权限")
    print("3. 或者需要特定的请求头或认证信息")
    
    return False

if __name__ == "__main__":
    print("开始下载'人工智能对就业市场的影响数据集.pdf'文件...")
    start_time = time.time()
    
    # 先删除可能存在的空文件
    if os.path.exists(save_path) and os.path.getsize(save_path) == 0:
        print(f"删除空文件: {save_path}")
        os.remove(save_path)
    
    success = try_different_urls()
    
    if success:
        print("\n下载任务成功完成！")
    else:
        print("\n下载任务失败。")
        print("建议获取包含此PDF链接的HTML文件，然后使用之前的批处理脚本来下载。")
    
    end_time = time.time()
    print(f"总耗时: {end_time - start_time:.2f} 秒")